﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using Microsoft.Practices.ServiceLocation;
using NinjectAdapter;
using CCM.CronTaskScheduler;

namespace CCM.ConsoleTest {
    class Program {
        static void Main(string[] args) {
            BootStrap();
            var sm = ServiceLocator.Current.GetInstance<IScheduleManager>();
            var notificationProvider = ServiceLocator.Current.GetInstance<INotificationProvider>();
            notificationProvider.AddRunCompleteHandler(r => {
                Console.WriteLine("Task was run: {0}", r.TaskDefinition.TaskName);
                Console.WriteLine("Success? {0}", r.Success);
                Console.WriteLine("Message: {0}", r.Message);
            });
            var def = new TaskDefinition {
                TaskName = "Task 1",
                TaskType = typeof(MyTask),
                CustomData = new Dictionary<string, object>() {
                    {"data1key","data1value"},
                    {"data2key","data2value"}
                }
            };
            MyTask.CallBack = () => {
                Console.WriteLine("MyTask ran at: {0}", DateTime.Now);
            };
            var someTimeFromNow = DateTime.Now.AddMinutes(2);
            var cron = string.Format("0-59 * * * *");
            Console.WriteLine("Cron schedule: {0}", cron);
            Console.WriteLine("Current Time: {0}", DateTime.Now);

            sm.AddTaskDefinition(cron, def);
            sm.AddTaskDefinition(cron, new TaskDefinition {
                TaskType = typeof(MyExceptioningTask),
                TaskName = "Task with Exception"
            });

            sm.Start();
            Console.WriteLine("Press <ENTER> to continue....");
            Console.ReadLine();
            sm.Stop(forceClose: true);
        }

        private static void BootStrap() {
            IKernel kernel = new StandardKernel(new TestKernel());
            var locator = new NinjectServiceLocator(kernel);
            ServiceLocator.SetLocatorProvider(() => locator);
        }
    }

    public class MyExceptioningTask : StandardTask {

        public override bool Execute(Dictionary<string, object> customData) {
            throw new NotImplementedException();
        }
    }

    public class MyTask : StandardTask {

        public static Action CallBack { get; set; }

        public override bool Execute(Dictionary<string, object> customData) {
            foreach (var item in customData) {
                Console.WriteLine("{0}=>{1}", item.Key, item.Value);
            }
            if (CallBack != null)
                CallBack();
            return true;
        }
    }
}
